package com.demo.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;

import java.io.IOException;
import java.util.Properties;

/**
 * 从apollo数据中心读取配置信息
 * @Author graham
 * @Date 2020.10.30
 */
public class ApolloSettings {

    /**
     * 多环境apollo meta server，通过静态系统变量自动匹配并配置
     * SPI自动关联apollo-env.properties文件
     * @Link https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/Env.java
     */
    static void environmentSetting(){
        String environment = ProjectSettings.getInstance().getProperty("environment").toLowerCase();

        switch (environment) {
            case "xxxxx1":
                environment = "uat";
                break;
            case "xxxxx2":
                //apollo official no sit statement。So use FAT: Feature Acceptance Test environment
                environment = "fat";
                break;
            case "xxxxx3":
                environment = "pro";
                try {
                    Properties properties = new Properties();
                    properties.load(ApolloSettings.class.getResourceAsStream("/apollo-env.properties"));
                    // prod环境通过meta server地址自动发现的config service不可用，怀疑prod环境apollo配置做了单独设置，
                    // 故需要跳过meta server服务发现步骤，直接配置系统全局config service地址，目前该地址和meta server地址一致
                    System.setProperty("apollo.configService", properties.getProperty("pro.meta"));
                } catch (IOException e) {
                    System.out.println("加载apollo-env.properties文件失败！");
                }
                break;
        }
        System.setProperty("env", environment);
    }

    /**
     * 获取数据库账户密码所有配置
     * @return
     */
    public static Properties dbConfgEntity() {
        String dbNamespace = "xxxxx.api-test.db-cfg";
        return apolloEntity(dbNamespace);
    }

    /**
     * 获取测试账号所有配置
     * @return
     */
    public static Properties accountConfgEntity() {
        String accountNamespace = "xxxxx.api-test.account-common";
        return apolloEntity(accountNamespace);
    }

    /**
     * 获取offer类型
     * @return
     */
    public static Properties campaignSubtype() {
        String accountNamespace = "xxxxx.api-test.campaign_subtype";
        return apolloEntity(accountNamespace);
    }

    /**
     * 获取apollo实例并返回namespace全部Key:Value
     * @param namespace
     * @return
     */
    private static Properties apolloEntity(String namespace){
        environmentSetting();
        Config config = ConfigService.getConfig(namespace);
        Properties properties = new Properties();

        for (String keyName : config.getPropertyNames()) {
            properties.setProperty(keyName, config.getProperty(keyName, "DefaultValueNull"));
        }

        System.out.println("加载apollo配置中心数据完成！");
        return properties;
    }
}
